package com.xyz.dao;

import com.xyz.Mapper.StudentMapper;
import com.xyz.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Qualifier("studentDao")
public class StudentDaoImpl implements StudentDao {
    // 自动注入 JdbcTemplate
    @Autowired
    JdbcTemplate jdbcTemplate;

    // 实现数据插入接口
    public void create(String name, Integer age) {
        // inset 语句，后面用了两个参数
        String SQL = "insert into Student (name, age) values (?, ?)";
        // JdbcTemplate 的 update 方法用来执行更改数据库数据的操作：插入、删除或更新
        // 第一个参数是要执行的 SQL 语句
        // 后面可以有0个或多个参数，对应于 Sql 语句中的参数，按顺序排
        jdbcTemplate.update( SQL, name, age);
        System.out.println("Created Record Name = " + name + " Age = " + age);
        return;
    }
    // 实现根据 id 查找学生的方法
    public Student getStudent(Integer id) {
        String SQL = "select * from Student where id = ?";
        Student student = jdbcTemplate.queryForObject(SQL,
                new Object[]{id}, new StudentMapper());
        return student;
    }
    // 查找全部学生
    public List<Student> listStudents() {
        String SQL = "select * from Student";
        List <Student> students = jdbcTemplate.query(SQL,
                new StudentMapper());
        return students;
    }
    // 删除指定 id 的学生
    public void delete(Integer id){
        String SQL = "delete from Student where id = ?";
        jdbcTemplate.update(SQL, id);
        System.out.println("Deleted Record with ID = " + id );
        return;
    }
    // 根据 id 更新年龄
    public void update(Integer id, Integer age){
        String SQL = "update Student set age = ? where id = ?";
        jdbcTemplate.update(SQL, age, id);
        System.out.println("Updated Record with ID = " + id );
        return;
    }
}
